package org.praktika.api.service;

import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.praktika.api.dto.TurOrderDto;
import org.praktika.api.entity.TurOrder;
import org.praktika.api.repository.TurOrderRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class TurOrderService {
    private final TurOrderRepository turOrderRepository;
    private final ClientService clientService;
    private final EmployeeService employeeService;
    private final ModelMapper modelMapper = new ModelMapper();

   @Transactional
    public TurOrderDto saveTurOrder  (TurOrderDto turOrderDto){
       TurOrder turOrder = modelMapper.map(turOrderDto, TurOrder.class);
       turOrderRepository.save(turOrder);
       return modelMapper.map(turOrder, TurOrderDto.class);
   }

   public TurOrderDto getTurOrderDtoById   (Long id){
       return modelMapper.map(getTurOrderById(id), TurOrderDto.class);

   }
   public TurOrder getTurOrderById    (Long id){
       Optional<TurOrder> turOrder = turOrderRepository.findById(id);
       return turOrder.orElseThrow(() -> new RuntimeException("No tur order found"));
   }

   @Transactional
    public TurOrderDto updateTurOrder(TurOrderDto turOrderDto){
       TurOrder turOrder = getTurOrderById(turOrderDto.getId());
       turOrder.setDate(turOrderDto.getDate());
       turOrder.setClient(clientService.getClientById(turOrderDto.getClient().getId()));
       turOrder.setEmployee(employeeService.getEmloyeeById(turOrderDto.getEmployee().getId()));
       turOrder.setPrice(turOrderDto.getPrice());
       turOrderRepository.save(turOrder);
       return modelMapper.map(turOrder, TurOrderDto.class);
   }

   @Transactional
    public void deleteTurOrder(Long id){
       turOrderRepository.deleteById(id);
   }

   public List<TurOrderDto> findAllTurOrders(){
       List<TurOrder> turOrders = turOrderRepository.findAll();
       List<TurOrderDto> turOrderDtos = new ArrayList<>();
       for (TurOrder turOrder : turOrders) {
           turOrderDtos.add(modelMapper.map(turOrder, TurOrderDto.class));
       }
       return turOrderDtos;

   }
}
